using System.Collections;
using System.Collections.Generic;
using UnityEngine;


public class EventSubscriber<TArgs> {

	public EventSubscriber() {
		//target+=TargetEventHandler;
		singleSubscribtions=new Dictionary<object,System.EventHandler<TArgs>>();
	}

	public virtual void TargetEventHandler(object sender,TArgs e) {
		allSubscribtions?.Invoke(sender,e);
		if(singleSubscribtions.ContainsKey(sender))
			singleSubscribtions[sender].Invoke(sender,e);
	}

	protected System.EventHandler<TArgs> allSubscribtions;
	protected Dictionary<object,System.EventHandler<TArgs>> singleSubscribtions;

	public void SubscribeAll(System.EventHandler<TArgs> handler) {
		allSubscribtions+=handler;
	}
	public void UnsubscribeAll(System.EventHandler<TArgs> handler) {
		allSubscribtions-=handler;
	}

	public void SubscribeSingle(object sender,System.EventHandler<TArgs> handler) {
		if(sender==null) {
			throw new System.Exception();
		}
		if(singleSubscribtions.ContainsKey(sender)) {
			singleSubscribtions[sender]+=handler;
		} else {
			singleSubscribtions.Add(sender,handler);
		}
	}

	public void UnsubscribeSingle(object sender,System.EventHandler<TArgs> handler) {
		if(sender==null) {
			throw new System.Exception();
		}
		if(!singleSubscribtions.ContainsKey(sender)) return;

		singleSubscribtions[sender]-=handler;
		if(singleSubscribtions[sender]==null)
			singleSubscribtions.Remove(sender);

	}
}

public class EventSubscriber:EventSubscriber<object> {
	public void TargetEventHandler(object sender) {
		base.TargetEventHandler(sender,null);
	}
}
